<?php

namespace App\Http\Controllers;

use App\Http\Requests\UsersForm;
use App\Models\Replies;
use App\Models\Topics;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{

    public function index(Request $request)
    {

        if (isset($request->id)) {
            $user = User::query()->find($request->id);
        } else {
            $user = Auth::user();
        }
        $topics  = null;
        $replies = null;
        if (isset($_GET['tab']) && $_GET['tab'] == 'replies') {
            $replies = Replies::query()->with('topic', 'topic.category')->where('user_id', $user->id)->paginate(10);
        } else {
            $topics = Topics::query()->where('user_id', $user->id)->with('category')->paginate(10);
        }

        return view('user.index', ['user' => $user, 'topics' => $topics, 'replies' => $replies]);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        $user     = Auth::user();
        $response = [
            'id'           => $user->id,
            'name'         => $user->name,
            'email'        => $user->email,
            'introduction' => $user->introduction,
            'avatar'       => addslashes($user->avatar),
        ];

        return view('user.edit', ['user' => $response]);
    }

    public function getCurrentUser()
    {
        $user     = Auth::user();
        $response = [
            'id'           => $user->id,
            'name'         => $user->name,
            'email'        => $user->email,
            'introduction' => $user->introduction,
            'avatar'       => $user->avatar,
        ];
        return response()->json($response);
    }

    public function update(UsersForm $request)
    {
        $params = $request->all();
        $this->authorize('update', User::find($params['id']));
        $res = User::query()->where('id', $params['id'])->update([
            'name'         => $params['name'],
            'introduction' => $params['introduction'],
            'avatar'       => $params['avatar'],
        ]);
        if ($res) {
            return response()->json(['status' => true]);
        } else {
            return response()->json(['status' => false]);
        }
    }
}
